﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WinnerCMS.CacheStorager;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// GatherManage 的摘要说明。
    /// </summary>
    public class GatherManage : MarshalByRefObject
    {
        private static readonly GatherDal Dal;

        static GatherManage()
        {
            Dal = new GatherDal();
        }

        #region 添加文章采集规则

        /// <summary>
        /// 添加文章采集规则
        /// </summary>
        /// <param name="model"></param>
        [Logging, ExceptionCall]
        public Result Save(Gather model)
        {
            Result res = new Result();
            string[] textArray1 = model.Filter.Split('\n');
            string[] textArray2 = model.Replace.Split('\n');

            if (textArray1.Length != textArray2.Length)
            {
                res.Errors = "“过滤内容”和被“被替换为”的行数要一致\\n“过滤内容”为" + textArray1.Length + "行\\n“被替换为”也应该为" + textArray1.Length +
                          "行";
            }
            else
            {
                if (model.Id == 0)
                {
                    model.CheckInTime = DateTime.Now;
                    Dal.Add(model);

                    res.LogMessage = "添加文章采集规则" + model.Name;
                }
                else
                {
                    Dal.Edit(model);

                    res.LogMessage = "修改文章采集规则" + model.Id;
                }
            }
            if (string.IsNullOrEmpty(res.Errors))
            {
                CMSCaches.Context.RemoveLike("WinnerCMS.ArticleGather");
            }
            return res;
        }

        #endregion

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Gather GetInfo(int id)
        {
            Gather info;
            if (CMSCaches.Context.TryGet("WinnerCMS.ArticleGather.GetInfo" + id, out info) == false)
            {
                info = Dal.GetInfo(id);
                CMSCaches.Context.Add("WinnerCMS.ArticleGather.GetInfo" + id, info, DateTimeType.Second, 600);
            }
            return info;
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="keyWord"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Gather> BindList(byte modelId, string keyWord, PagingParam pp)
        {
            return Dal.BindList(modelId, keyWord, pp);
        }

        /// <summary>
        /// 删除采集规则
        /// </summary>
        /// <param name="id"></param>
        [Logging("删除采集规则，Id：{@p0}"), ExceptionCall]
        public void Delete(string id)
        {
            Dal.Delete(int.Parse(id));
        }

        /// <summary>
        /// 复制采集任务
        /// </summary>
        /// <param name="name"></param>
        public void Copy(ListControl name)
        {
            name.DataSource = Dal.Copy();
            name.DataTextField = "Name";
            name.DataValueField = "ID";
            name.DataBind();
            name.Items.Insert(0, new ListItem("--请选择任务--", "0"));
        }

        /// <summary>
        /// 绑定节点
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public IList<Gather> BindNode(int pid)
        {
            return Dal.NodeBind(pid);
        }

        /// <summary>
        /// 获取采集规则
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="modelId"></param>
        /// <returns></returns>
        public IList<Gather> GetRules(string ids, byte modelId)
        {
            string key = "WinnerCMS.ArticleGather.GetRules_" + modelId + "_" + ids;
            IList<Gather> list;
            if (CMSCaches.Context.TryGet(key, out list) == false)
            {
                list = Dal.GetRules(MyConvert.ConvertToArr(ids), modelId);
                if (list.Count > 0)
                    CMSCaches.Context.Add(key, list, DateTimeType.Hour, 1);
            }
            return list;
        }

        /// <summary>
        /// 缓存下一页
        /// </summary>
        /// <param name="pageUrl"></param>
        /// <param name="urls"></param>
        /// <remarks>只有大于等于5页才进行缓存</remarks>
        public void CacheNextPages(string pageUrl, string[] urls)
        {
            if (urls.Length < 4)
                return;
            GatherUrlCache[] infos = (from x in urls
                                      select
                                          new GatherUrlCache
                                          {
                                              PUrl = pageUrl,
                                              PUrlMD5 = Hash.Md5(pageUrl),
                                              NextPageUrl = x,
                                              CacheTime = DateTime.Now
                                          }).ToArray();

            new GatherUrlCacheDal().Cache(infos);
        }

        /// <summary>
        /// 读取缓存的url地址
        /// </summary>
        /// <param name="pageUrl"></param>
        /// <returns></returns>
        public string[] ReadNextPages(string pageUrl)
        {
            return new GatherUrlCacheDal().ReadNextPages(Hash.Md5(pageUrl));
        }

        /// <summary>
        /// 最后一次工作时间
        /// </summary>
        /// <param name="id"></param>
        public void LastWork(int id)
        {
            Dal.LastWork(id);
        }

        /// <summary>
        /// 启用或者禁用
        /// </summary>
        /// <param name="id"></param>
        [Logging("启用或者禁用采集规则，Id：{@p0}"), ExceptionCall]
        public void DisableOrUsedIt(int id)
        {
            Dal.DisableOrUsedIt(id);
        }
    }
}